package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.query.RegionQuery;
import cn.wolfcode.wolf2w.repository.RegionRepository;
import cn.wolfcode.wolf2w.service.IRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;

@Service
public class RegionServiceImpl implements IRegionService {
    @Autowired
    private RegionRepository regionRepository;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void insert(Region region) {
        //因为我们前端传过来时可能是空字符串,此时到数据库是不会解析它的
        region.setId(null);
        regionRepository.save(region);
    }

    @Override
    public void delete(String id) {
        regionRepository.deleteById(id);
    }

    @Override
    public void update(Region region) {
        regionRepository.save(region);
    }

    @Override
    public Region selectOne(String id) {
        Optional<Region> region = regionRepository.findById(id);
        return region.orElse(null);
    }

    @Override
    public List<Region> list() {
        return null;
    }

    @Override
    public Page<Region> query(RegionQuery qo) {
        Query query = new Query();

        //先判断是否有数据
        long total = mongoTemplate.count(query, Region.class);

        if (total == 0){
            return Page.empty();
        }

        //拼接条件进行当前页的数据查询
        Pageable request = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        query.with(request);
        List<Region> regions = mongoTemplate.find(query, Region.class);

        //给予三个参数返回的是一个类似PageResult
        return new PageImpl<>(regions, request, total);
    }

    @Override
    public void changeHotValue(String id, int hot) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.set("ishot", hot);
        mongoTemplate.updateMulti(query,update,Region.class);
    }

    @Override
    public List hotRegion() {
       List hot =  regionRepository.findByIshotOrderBySequence(1);
        return hot;
    }

}
